<template>
    <el-upload
      class="avatar-uploader"
      :action="`/api/goods/goods_img_upload`"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :headers="uploadHeaders"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
  </template>
  
  <script lang="ts" setup>
  import { ref, watch } from 'vue';
  import { ElMessage } from 'element-plus';
  import { Plus } from '@element-plus/icons-vue';
  import type { UploadProps } from 'element-plus';
  import { serverUrl } from '@/utils/common';
  
  const imageUrl = ref('');
  const emit = defineEmits(['update']);
  
  // 动态附加请求头
  const uploadHeaders = ref({
    Authorization: `Bearer ${sessionStorage.getItem('token')}`,
  });
  
  // 上传成功回调
  const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
    if (response.code === 0 && response?.imgUrl) {
      // 拼接完整的图片 URL
      emit('update', response.imgUrl);
      // 更新图片 URL
      imageUrl.value = `${serverUrl}${response.imgUrl}`;
      ElMessage.success('商品图片上传成功！');
      
      console.log('上传成功后的图片 URL:', imageUrl.value);
    } else {
      ElMessage.error('商品图片上传失败，请稍后重试');
    }
  };
  
  // 上传前校验
  const beforeAvatarUpload= (rawFile) => {
    if (!rawFile.type.includes('image')) {
      ElMessage.error('必须为图片格式！');
      return false;
    } else if (rawFile.size / 1024 > 50) {
      ElMessage.error('图片大小不能超过 50KB！');
      return false;
    }
    return true;
  };
  </script>
  
  <style scoped>
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  </style>
  
  <style>
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
  </style>